package com.example.demo2.config;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

/**
 * Created with IntelliJ IDEA
 * Description：统一异常处理
 * User：chenshu
 * Date：2023-12-31
 * Time：22:42
 */
@ControllerAdvice
public class ErrorAdvice {

    //默认异常处理
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public HashMap<String, Object> exceptionAdvice(Exception e) {
        HashMap<String, Object> ret = new HashMap<>();
        ret.put("code", "-1");
        ret.put("msg", e.getMessage());
        return ret;
    }

    //算数异常处理
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public HashMap<String, Object> arithmeticAdvice(Exception e) {
        HashMap<String, Object> ret = new HashMap<>();
        ret.put("code", "-2");
        ret.put("msg", e.getMessage());
        return ret;
    }

}
